package com.mytest.provider.mg;

import com.mytest.provider.mg.mapper.UserDao;
import com.mytest.provider.mg.pojo.UserMg;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import javax.annotation.Resource;

/**
 * @Author: llq
 * @Date: 2020/5/7
 */
@Configuration
public class MgServiceImpl implements UserDao {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void saveUser(UserMg userMg) {
        mongoTemplate.save(userMg);
    }

    @Override
    public void removeUser(Long id) {
//        mongoTemplate.remove(id);

        UserMg userMg = new UserMg();
        userMg.setId(id);
        mongoTemplate.remove(userMg);
    }

    @Override
    public void updateUser(UserMg userMg) {
        Query query = new Query(Criteria.where("id").is(userMg.getId()));

        Update update = new Update();
        update.set("username", userMg.getUsername());
        update.set("password", userMg.getPassword());
        update.set("nickname", userMg.getNickName());
        update.set("id", userMg.getId());

        mongoTemplate.updateFirst(query, update, UserMg.class);
    }

    @Override
    public UserMg findUserById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        UserMg userMg = mongoTemplate.findOne(query, UserMg.class);
        return userMg;
    }
}
